package br.com.faculdade.infrastructure.dao;

import br.com.faculdade.infrastructure.entity.ReservaEstadia;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.TransactionPropagationType;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.log.Log;

/**
 * Classe de acesso aos dados de Reserva e estadias
 * @author Kirmaier
 */
@AutoCreate
@Name("reservaEstadiaDAO")
@Transactional(TransactionPropagationType.SUPPORTS)
public class ReservaEstadiaDAO implements Serializable {

    @In
    private Session reservaDB;
    @Logger
    private Log log;

    public void alterar(ReservaEstadia reserva) {
        log.info("Alterando reserva");

        reservaDB.saveOrUpdate(reserva);
        reservaDB.flush();
    }

    public void cancelar() {
        log.info("Cancelando operação");

        reservaDB.flush();
    }

    public void excluir(ReservaEstadia reserva) {
        log.info("Excluir reserva");

        reservaDB.delete(reserva);
        reservaDB.flush();
    }

    public ReservaEstadia obterPorId(Integer idreserva) {
        log.info("Buscando reservaEstadia por ID");

        return (ReservaEstadia) reservaDB.get(ReservaEstadia.class, idreserva);
    }

    public List<ReservaEstadia> obterPorParametros(Date paramDataChegada, Date paramDataMarcacao, Short paramStatusReserva, Integer paramTipoApartamento, String paramHospede) {
        log.info("Buscando reservas");

        Criteria c = reservaDB.createCriteria(ReservaEstadia.class);
        c.addOrder(Order.asc("idreserva"));

        if (paramDataChegada != null) {
            c.add(Restrictions.eq("datachegada", paramDataChegada));
        }
        if (paramDataMarcacao != null) {
            c.add(Restrictions.eq("datamarcacao", paramDataMarcacao));
        }
        if (paramStatusReserva != null) {
            c.add(Restrictions.eq("reserva", paramStatusReserva));
        }
        if (paramTipoApartamento != null) {
            c.createAlias("apartamento", "ap");
            c.createAlias("ap.tipoApartamento", "tp");
            c.add(Restrictions.eq("tp.idtipo", paramTipoApartamento));
        }
        if (paramHospede != null && !paramHospede.isEmpty()) {
            c.createAlias("hospede", "hospede");
            c.add(Restrictions.ilike("hospede.nome", paramHospede, MatchMode.ANYWHERE));
        }

        return c.list();
    }

    public void salvar(ReservaEstadia reserva) {
        log.info("Salvar objeto no banco");

        reservaDB.save(reserva);
    }
}
